require "bundler/gem_tasks"
require 'rubygems'
require 'less'
require 'rake'
require 'fileutils'

desc "Build the static precompiled stylesheets from Less sources"
task :build_static_stylesheets do

	CONFIG = {
	'less' => File.path( 'vendor/uikit/src/less' ),
	'css' =>  File.path( 'app/assets/stylesheets' ),
	'fonts_source' => File.path( 'vendor/uikit/src/fonts' ),
	'fonts_destination' => File.path( 'app/assets/stylesheets/fonts' ),
	'input' =>  "uikit.less",
	'output' => "uikit.css",
	'components' => 'components',
	'components_destination' => 'uikit_components',
	'themes' => 'vendor/uikit/themes'
	} 

	COMPONENTS = %w(	
					autocomplete.less
					caption.less
					cover.less
					datepicker.less
					dotnav.less
					flex.less
					form-advanced.less
					form-file.less
					form-password.less
					form-select.less
					htmleditor.less
					nestable.less
					notify.less
					placeholder.less
					search.less
					slidenav.less
					slideshow.less
					sortable.less
					sticky.less
					upload.less	)

	THEMES = %w( almost-flat gradient )

	FileUtils.mkpath (File.join( CONFIG['css'], CONFIG['components_destination'] ))

	# Create static stylesheets from less source for UIKit core

	input  = File.join( CONFIG['less'], CONFIG['input'] )
	output = File.join( CONFIG['css'], CONFIG['output'] )

	source = File.open( input, "r" ).read
 	
 	parser = Less::Parser.new( :paths => [CONFIG['less']] )
	tree = parser.parse( source )
 
	File.open( output, "w+" ) do |f|
		f.puts tree.to_css( :compress => true )
	end 

	# Create stylesheets for themes

	THEMES.each do |t|
		input  = File.join( CONFIG['themes'], t, CONFIG['input'] )
		output = File.join( CONFIG['css'], CONFIG['output'].gsub(/.css/, ".#{t}.css") )

		source = File.open( input, "r" ).read
	 	
	 	parser = Less::Parser.new( :paths => [ File.join( CONFIG['themes'], t ) ] )
		tree = parser.parse( source )
	 
		File.open( output, "w+" ) do |f|
			f.puts tree.to_css( :compress => true )
		end 
	end

	# Create static stylesheets from less source for UIKit components

	COMPONENTS.each do |c|

		input  = File.join( CONFIG['less'], CONFIG['components'], c )
		output = File.join( CONFIG['css'], CONFIG['components_destination'], c.gsub(/.less/, '.css') )

		source = "@import 'vendor/uikit/src/less/core/variables.less';\n" + File.open( input, "r" ).read
	 	
	 	parser = Less::Parser.new( :paths => [CONFIG['less']] )
		tree = parser.parse( source )
	 
		File.open( output, "w+" ) do |f|
			f.puts tree.to_css( :compress => true )
		end 

	end

	# Then copy fonts
	FileUtils.copy_entry CONFIG['fonts_source'], CONFIG['fonts_destination']
end